/***************************************************************************
 *            binnote.cc
 *
 *  Sat Nov 19 21:16:57 2005
 *  Copyright  2005  Robin Shao
 *  swjbook@yahoo.com
 ****************************************************************************/

/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include "binnote.h"
#include "CodeConverter.h"
extern CodeConverter u2g, g2u;
binnote::binnote ()
{
  // printf ("default");
}
binnote::binnote (const int user_id, const int friend_id)
{
  sprintf (filename, "%s%d%d.note", GUnit::getLogPath (), user_id, friend_id);
  // filename like 1498507712345.note
  // GUnit::getLogPath() will give out 
  head.qqnum = user_id;
  head.file_version = FILEVERSION;
  head.last_position = BODYSTART;
  head.last_date=0;//will update in a new file.
  head.date_count=0;//if a new file.
  read_offset = 0;// this is the current read position
  // these pointers will store the read and write position
  if (file_exists (filename))
    {
      printf ("using an old chatlog file.\n");
      try
      {
	datafile.open (filename, ios::binary | ios::out | ios::in);
      }
      catch (exception & e)
      {
	cout << e.what () << endl;
      }
      if (!read_head ())
	write_head ();
    }
  else
    {
      cout << "building a new chatlog file!\n";
      try
      {
	datafile.open (filename, ios::out);
      }
      catch (exception & e)
      {
	cout << e.what () << endl;
      }
      if (datafile.good () == false)
	cout << "fail to open" << filename << endl;
      else
	{
	  datafile << "#";
	  datafile.close ();
	}
      try
      {
	datafile.open (filename, ios::binary | ios::out | ios::in);
      }
      catch (exception & e)
      {
	cout << e.what () << endl;
      }
    }
  if (datafile.good () == false)
    cout << "fail to open" << filename << endl;
  else
	cout<<"it's ok"<<endl;

}

int
binnote::file_exists (const char *fileName)
{
  struct stat buf;
  int i = stat (fileName, &buf);
  if (i == 0)
    {
      return 1;
    }
  return 0;

}

binnote::~binnote ()
{
  write_head ();		// update the head info
  datafile.close ();
}

// we have made big change to write_msg()
bool
  binnote::write_msg (const int qqnum,
		      const string nickname,
		      const int time_msg, const string msg)
{
  int position = 15;
  // 15 is just a lucky number,Yahoo!
  // only used to reserve a position for the right number
  // position is used as a pointer to next msg;
  // only to reserve a position for pointer
  write_it (position,head.last_position);
  write_it (time_msg);
  write_it (qqnum);
  write_it (nickname);
  write_it (msg);
  write_it (head.last_position);
  // here we make a pointer backward 
  // pointing to the begin of the message,later used to go backward.
  position = datafile.tellp ();
  write_it (position,head.last_position);
  // write down the end position of the msg
  // actually it's also the begin of next msg
 
  cout<<date2int(time_msg)<<" "<<head.last_date<<endl;
  if(date2int(time_msg)>head.last_date)
  {
	  cout<<"new date entered!"<<endl;
	  head.index[head.date_count].date=date2int(time_msg);
	  head.index[head.date_count].offset=head.last_position;
	  head.last_date=date2int(time_msg);
	  head.date_count++;
  }
   head.last_position = position;
  // update the last_position pointer
  //check if we need update the index
  return false;
}

int binnote::set_start_date(int start_date)
{
	if(start_date>head.last_date)
	{
		cout<<"error happensed"<<endl;
		cout<<"start_date="<<start_date<<endl;
		cout<<"max_date="<<head.last_date<<endl;
		cout<<head.date_count<<endl;
		return -1;
	}
	else{
	for(int i=0;i<head.date_count;i++)
	{
		cout<<"off="<<head.index[i].date<<"and start_date="<<start_date<<endl;
		if(start_date>head.index[i].date)
		{
			continue;
		}
		else 
		{
			read_offset=head.index[i].offset;
			break;
		}
	}
	}
	return 0;
}
int binnote::set_end_date(int end_date)
{
	if(end_date<head.index[0].date)
		return -1;
	else
		return 0;
}
int
  binnote::read_msg (int &qqnum, string & nickname, int &time_msg,
		     string & msg)
{
  //bool ret = false;

  // use static var to store the last read position
  if (read_offset == 0)
    read_offset = FIRSTPOS;
  // cout<<endl<<"read pointer changed"<<read_offset<<endl;
  // first time read ,set it to the default begin_position
  if ((read_offset >= head.last_position) || datafile.eof ()
      || read_offset <= 0)
    {
      read_offset = FIRSTPOS;
	cout<<"a abnormal case\n";
	return -1;//special for end the reading
      // reset to the head after read through all data
      //ret = read_offset;
    }
  else
    {
      try
      {
	datafile.seekg (read_offset);
      }
      catch (exception & e)
      {
	cout << e.what () << endl;
      }
      read_it (read_offset);//pointer to next message
      read_it (time_msg);
      read_it (qqnum);
	  read_it (nickname);
	  read_it (msg);
		//read_it(pointer to previous message)
		//will be used in the future
	}
  // cout<<endl<<"read pointer changed:"<<read_offset<<endl; 
  return read_offset;
}

bool
binnote::write_head ()
{
  write_it ("QQDATA", OFF_FILEMARK);	// 按说这里写的肯定是对了
  write_it (head.file_version, OFF_FILEVERSION);
  write_it (head.qqnum, OFF_QQNUM);
//  write_it (head.first_position, OFF_FIRSTPOS);
	//fixed position ,no need to save and change it.
  write_it (head.last_position, OFF_LASTPOS);
//  write_it (head.first_date, OFF_FIRSTDATE);
	//no need in this version at least.
  write_it (head.last_date, OFF_LASTDATE);
  write_it (head.date_count, OFF_COUNTDATE);
  for (int i = 0; i < head.date_count; i++)
    {
      write_it (head.index[i].date);
      write_it (head.index[i].offset);
	cout<<i<<","<<head.index[i].date<<endl;
    }
  for (int i = head.date_count;i<1000; i++)
    {
      write_it (0);
      write_it (0);
    }
  return false;
}

bool
binnote::read_head ()
{
  string file_mark = "";
  int file_version = 0;
  int qqnum = 0;
  bool ret = false;
  read_it (file_mark, OFF_FILEMARK);
  if (file_mark != "QQDATA")
    // here should check file_mark,anyway,it always fail,i hate this
    {
      cout << "Not a valid datafile with a name:" << filename << endl;
      cout << "please delete it from your subfolder!\n";
      ret = true;
    }
  else
    {
      read_it (file_version, OFF_FILEVERSION);
      // file version
      if (head.file_version != file_version)
	{
	  ret = true;
	  cout << "Not correct version of qqdata file\n";
	}
      else
	{
	  read_it (qqnum, OFF_QQNUM);
	  if (head.qqnum != qqnum)
	    {
	      ret = true;
	      cout << "Not correct qqdata with qqnum" << qqnum << endl;
	    }
	  else
	    {
	     // read_it (head.first_position, OFF_FIRSTPOS);
	      read_it (head.last_position, OFF_LASTPOS);
	     // read_it (head.first_date, OFF_FIRSTDATE);
	      read_it (head.last_date, OFF_LASTDATE);
	      read_it (head.date_count, OFF_COUNTDATE);
	      for (int i = 0; i < head.date_count; i++)
		{
		  read_it (head.index[i].date);
		  read_it (head.index[i].offset);
		}
	      for (int i = head.date_count;i<1000; i++)
		{
		  head.index[i].date = 0;
		  head.index[i].offset = 0;
		}
	    }

	}
    }
  return ret;
}

int
binnote::write_it (int i, int offset )
{
  if (offset != -1)		// -1 is defaut value,which will keep the
    // write pointer from moving.
    datafile.seekp (offset, ios_base::beg);
  datafile.write ((char *) &i, (long) sizeof (i));
  return sizeof (i);
}

int
binnote::read_it (int &i, int offset )
{
  // cout<<datafile.tellg()<<endl;
  if (offset != -1)		// -1 is defaut value,which will keep the
    // write pointer from moving.
    datafile.seekg (offset, ios_base::beg);
  datafile.read ((char *) &i, (long) sizeof (i));
  return sizeof (i);
}

int
binnote::write_it (const string & i, int offset )
{
  if (offset != -1)		// -1 is defaut value,which will keep the
    // write pointer from moving.
    datafile.seekp (offset, ios_base::beg);
  write_it (strlen (i.c_str ()));
  // write down the length of str for read
  datafile.write ((char *) i.c_str (), (long) strlen (i.c_str ()));
  return strlen (i.c_str ());
}

int
binnote::read_it (string & i, int offset)
{
  if (offset != -1)		// -1 is defaut value,which will keep the
    // write pointer from moving.
    datafile.seekg (offset, ios_base::beg);
  int lenth = 0;
  read_it (lenth);
  // cout<<lenth<<"bytes to allocate!"<<endl;
  if (lenth <= 0)
    {
      i = "NULL string!";
      return 0;
    }
  char *temp;
  try
  {
    temp = new char[lenth + 1];
  }
  catch (exception & e)
  {
    cout << e.what () << endl;
  }
  temp[lenth] = '\0';
  // get the str lenth
  datafile.read (temp, (long) lenth);
  i = temp;
  // cout<<temp[lenth]<<endl;
  delete[]temp;
  temp = NULL;
  return lenth;
}

void
binnote::convert_time (int time_msg, string & timeout)
{
  // //////////////////////////////////////////////////////////////////
  struct tm *tm;
  tm = localtime (reinterpret_cast < time_t * >(&time_msg));
  char timetext[255];
  snprintf (timetext, 32, "(%04d-%02d-%02d %02d:%02d:%02d) ",
	    tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
	    tm->tm_hour, tm->tm_min, tm->tm_sec);
  timeout = timetext;
  // ///////////////////////////////////////////////////////////////////
}

int
binnote::date2int (int time_msg)
{
  struct tm *tm;
  tm = localtime (reinterpret_cast < time_t * >(&time_msg));
  return ((tm->tm_year + 1900) * 10000 + (tm->tm_mon + 1) * 100 +
	  (tm->tm_mday));
  // covert the time_msg to a int date format like 20061001
}

bool
binnote::export_txt (const string & txtname)
{
  bool ret = false;
  if (file_exists (txtname.c_str ()))
    ret = true;
  else
    {
      ofstream txtout (txtname.c_str ());
      txtout << "CYCLONE GENERATED CHATLOG FILE" << endl;
      txtout << "FILEMARK=" << FILEMARK << endl;
      txtout << "FILEVERSION=" << head.file_version << endl;
      txtout << "QQNUM=" << head.qqnum << endl;
      txtout << "HEAD END" << endl;
      int qqnum = 0;
      string nickname = "";
      int time_msg = 0;
      string str_time = "";
      string msg = "";
      string converted_msg = "";
      //bool time_only = false;
      while (read_msg (qqnum, nickname, time_msg, msg)!=-1)
	{
	  convert_time (time_msg, str_time);
	  txtout << str_time;
	  txtout << nickname << endl;
	  converted_msg = g2u.convert (msg);
	  txtout << converted_msg << endl;
	}
      // binnote::read_msg (int &qqnum, string & nickname, int
      // &time_msg,
      // string & msg,bool time_only)

      txtout.close ();
      ret = false;
    }
  return ret;
}

